/*
 * @Author: zjj 
 * @Date: 2018-01-06 23:36:04 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2018-05-13 11:05:49
 */
import wepy from 'wepy'
import {reqUrl, reqHead, reqType, reqTip} from '../config'
import {toast, getAccessToken} from './component'
/**
 * 简单封装request请求
 * @param {*} url 请求地址
 * @param {*} data 发送数据
 * @param {*} isloading 是否开启加载动画 
 */
const $request = (url, data, isloading = false) => new Promise((resolve, reject) => {
  //开启加载动画
  isloading && wepy.showLoading({
    title: reqTip,
    mask: true
  });
  // 读取缓存access_token；
  let access_token = wepy.getStorageSync('access_token');
  if (!access_token) {
    getAccessToken(request);
    return false;
  }
  request();
  // 发起请求
  function request() {
    wepy.request({
      url: reqUrl + url,
      data,
      header: {
        ...reqHead,
        'access-token': wepy.getStorageSync('access_token')
      },
      method: reqType,
      dataType: reqType,
      // 请求成功
      success(res) {
        const {data} = res;
        const jsonData = JSON.parse(data);
        if (jsonData.code === 200) {
          resolve(jsonData.data);
        }else { 
          reject(jsonData)
        }
      },
      // 请求失败
      fail(err) {
        toast('请求发送失败，请稍后重试！');
      },
      // 请求结束
      complete() {
       wepy.hideLoading();
      }
    });
  }
});

export default $request;
